package com.hzj.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hzj.beans.News;
import com.hzj.beans.NewsType;
import com.hzj.forground.beans.IndexListItemBean;
import com.hzj.server.NewsServer;
import com.hzj.server.NewsTypeServer;

@WebServlet(
		name="IndexServlet",
		urlPatterns={"/IndexServlet.action"}
		
		)
public class IndexServlet extends HttpServlet{

	
	HttpServletRequest req;
	HttpServletResponse resp;
	
	ArrayList<NewsType> newsTypes;
	NewsTypeServer newsTypeServer;
	NewsServer newsServer;
	
	ArrayList<IndexListItemBean>indexListItemBeans;
	boolean tag = true;
	
	String mess="";
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.req=req;
		this.resp=resp;
		tag=true;
		newsServer=new NewsServer();
		newsTypeServer = new NewsTypeServer();
		indexListItemBeans = new ArrayList<IndexListItemBean>();
		try {
			newsTypes = newsTypeServer.findByAll();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mess = e.getMessage();
			req.setAttribute("mess", mess);
			req.getRequestDispatcher("mess.jsp").forward(req, resp);
			tag = false;
		}
		
		if(tag){
			try {
				for (NewsType newsTypeTemp : newsTypes) {
					IndexListItemBean indexListItemBean = new IndexListItemBean();
					indexListItemBean.setNewsType(newsTypeTemp);
					ArrayList<News>leftNews = newsServer.findByNewsTypeAnd1to3(newsTypeTemp.getId());
					ArrayList<News>rightNews = newsServer.findByNewsTypeAnd4to6(newsTypeTemp.getId());
					indexListItemBean.setLeftNews(leftNews);
					indexListItemBean.setRightNews(rightNews);
					indexListItemBeans.add(indexListItemBean);
				}
				
				
				
				req.setAttribute("indexListItemBeans", indexListItemBeans);
				req.setAttribute("NewsTypes", newsTypes);
				req.getRequestDispatcher("index.jsp").forward(req, resp);
				tag = false;
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mess = e.getMessage();
				req.setAttribute("mess", mess);
				req.getRequestDispatcher("mess.jsp").forward(req, resp);
				tag = false;
			}
				
			
		}
		
		
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

	
	
}
